<script>
export default {
  name: 'UploadImage',
  props: {
    /* 父组件传递过来的prop 图片路径 */
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    /* 头像上传之前的回调函数 */
    beforeUpload(file) {
      const isImg = file.type.indexOf('image') !== -1
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImg) this.$message.error('上传头像只能是图片!')
      if (!isLt2M) this.$message.error('上传头像图片大小不能超过 2MB!')
      return isImg && isLt2M
    },

    async handleRequest({ file }) {
      try {
        const formData = new FormData()
        formData.append('file', file)
        const imageUrl = await this.$store.dispatch('uploadStore/uploadAction', formData)
        this.$emit('input', imageUrl)
        this.$message.success('文件上传成功')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    handleSuccess() {
      this.$emit('uploadSuccess')
    }
  },
  emits: ['input', 'uploadSuccess']
}
</script>

<template>
  <el-upload class="image-uploader" action="#" :show-file-list="false" :on-success="handleSuccess" :before-upload="beforeUpload" :http-request="handleRequest">
    <img v-if="value" :src="value" class="image">
    <i v-else class="el-icon-plus image-uploader-icon "></i>
  </el-upload>
</template>

<style scoped lang="scss">
.image-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}

.image-uploader:hover {
  border: 1px dashed #ffc100;

}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.image {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
